package com.amt.olcacon;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class TablePlaceholderReplacer {
    
    public static void main(String[] args) throws Exception {
        // 加载模板文件
        InputStream is = new FileInputStream("src/main/resources/templates/LCA报告模板.docx");
        XWPFDocument doc = new XWPFDocument(is);
        
        // 替换表格占位符
        boolean replaced = replaceAllocationTablePlaceholder(doc);
        
        if (replaced) {
            System.out.println("表格占位符替换成功！");
        } else {
            System.out.println("未找到表格占位符！");
        }
        
        // 保存修改后的文档
        FileOutputStream out = new FileOutputStream("src/main/resources/templates/LCA报告_表格替换后.docx");
        doc.write(out);
        out.close();
        doc.close();
    }
    
    /**
     * 替换 {{ALLOCATION_TABLE}} 占位符为实际表格
     */
    public static boolean replaceAllocationTablePlaceholder(XWPFDocument doc) {
        // 遍历所有表格
        for (XWPFTable table : doc.getTables()) {
            // 检查每个单元格是否包含占位符
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    if (containsAllocationTablePlaceholder(cell)) {
                        System.out.println("找到包含 {{ALLOCATION_TABLE}} 的单元格");
                        
                        // 替换这个表格的内容
                        replaceTableWithData(table);
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    /**
     * 检查单元格是否包含表格占位符
     */
    private static boolean containsAllocationTablePlaceholder(XWPFTableCell cell) {
        String cellText = getCellText(cell);
        return cellText != null && cellText.contains("{{ALLOCATION_TABLE}}");
    }
    
    /**
     * 获取单元格的完整文本
     */
    private static String getCellText(XWPFTableCell cell) {
        StringBuilder text = new StringBuilder();
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            if (paragraph.getText() != null) {
                text.append(paragraph.getText());
            }
        }
        return text.toString();
    }
    
    /**
     * 用实际数据替换表格内容
     */
    private static void replaceTableWithData(XWPFTable table) {
        // 清空表格现有内容
        clearTable(table);
        
        // 创建表头
        createTableHeader(table);
        
        // 添加数据行
        addDataRows(table);
        
        // 设置表格样式
        setupTableStyle(table);
    }
    
    /**
     * 清空表格
     */
    private static void clearTable(XWPFTable table) {
        int rowCount = table.getNumberOfRows();
        for (int i = rowCount - 1; i >= 0; i--) {
            table.removeRow(i);
        }
    }
    
    /**
     * 创建表头
     */
    private static void createTableHeader(XWPFTable table) {
        XWPFTableRow headerRow = table.createRow();
        
        String[] headers = {"序号", "工序名称", "副产品名称", "分配方法", "分配系数", "描述"};
        
        for (int i = 0; i < headers.length; i++) {
            XWPFTableCell cell = headerRow.getCell(i);
            if (cell == null) {
                cell = headerRow.createCell();
            }
            setHeaderCell(cell, headers[i]);
        }
    }
    
    /**
     * 设置表头单元格
     */
    private static void setHeaderCell(XWPFTableCell cell, String text) {
        // 清空单元格
        for (int i = cell.getParagraphs().size() - 1; i >= 0; i--) {
            cell.removeParagraph(i);
        }
        
        XWPFParagraph paragraph = cell.addParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        run.setBold(true);
        run.setFontSize(10);
        run.setFontFamily("宋体");
        
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
    }
    
    /**
     * 添加数据行
     */
    private static void addDataRows(XWPFTable table) {
        // 生成示例数据
        List<TableRowData> dataList = generateTableData();
        
        for (int i = 0; i < dataList.size(); i++) {
            TableRowData data = dataList.get(i);
            XWPFTableRow dataRow = table.createRow();
            
            // 序号
            setDataCell(dataRow.getCell(0), String.valueOf(i + 1), true);
            // 工序名称
            setDataCell(dataRow.getCell(1), data.getProcessName(), false);
            // 副产品名称
            setDataCell(dataRow.getCell(2), data.getByProductName(), false);
            // 分配方法
            setDataCell(dataRow.getCell(3), data.getAllocationMethod(), false);
            // 分配系数
            setDataCell(dataRow.getCell(4), String.format("%.3f", data.getAllocationFactor()), true);
            // 描述
            setDataCell(dataRow.getCell(5), data.getDescription(), false);
        }
    }
    
    /**
     * 设置数据单元格
     */
    private static void setDataCell(XWPFTableCell cell, String text, boolean centerAlign) {
        if (cell == null) return;
        
        // 清空单元格
        for (int i = cell.getParagraphs().size() - 1; i >= 0; i--) {
            cell.removeParagraph(i);
        }
        
        XWPFParagraph paragraph = cell.addParagraph();
        if (centerAlign) {
            paragraph.setAlignment(ParagraphAlignment.CENTER);
        } else {
            paragraph.setAlignment(ParagraphAlignment.LEFT);
        }
        
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        run.setFontSize(9);
        run.setFontFamily("宋体");
        
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
    }
    
    /**
     * 设置表格样式
     */
    private static void setupTableStyle(XWPFTable table) {
        try {
            CTTbl ctTable = table.getCTTbl();
            CTTblPr tblPr = ctTable.getTblPr();
            if (tblPr == null) {
                tblPr = ctTable.addNewTblPr();
            }
            
            // 表格宽度 - 根据窗口自动调整
            CTTblWidth tblWidth = tblPr.addNewTblW();
            tblWidth.setType(STTblWidth.AUTO);
            tblWidth.setW(BigInteger.valueOf(0));
            
            // 表格边框
            CTTblBorders borders = tblPr.addNewTblBorders();
            setBorder(borders.addNewTop(), STBorder.SINGLE, 4, "000000");
            setBorder(borders.addNewLeft(), STBorder.SINGLE, 4, "000000");
            setBorder(borders.addNewBottom(), STBorder.SINGLE, 4, "000000");
            setBorder(borders.addNewRight(), STBorder.SINGLE, 4, "000000");
            setBorder(borders.addNewInsideH(), STBorder.SINGLE, 2, "000000");
            setBorder(borders.addNewInsideV(), STBorder.SINGLE, 2, "000000");
            
        } catch (Exception e) {
            System.err.println("设置表格样式时出错: " + e.getMessage());
        }
    }
    
    private static void setBorder(CTBorder border, STBorder.Enum style, int size, String color) {
        border.setVal(style);
        border.setSz(BigInteger.valueOf(size));
        border.setColor(color);
    }
    
    /**
     * 生成表格数据
     */
    private static List<TableRowData> generateTableData() {
        List<TableRowData> dataList = new ArrayList<>();
        
        dataList.add(new TableRowData(
            "黏合剂生产", 
            "工艺废水", 
            "物理分配法", 
            0.150, 
            "基于副产品与主产品的质量比例进行分配"
        ));
        
        dataList.add(new TableRowData(
            "金属加工", 
            "金属废料", 
            "经济价值法", 
            0.320, 
            "根据副产品市场价值与主产品总价值的比例分配"
        ));
        
        dataList.add(new TableRowData(
            "组件组装", 
            "废包装材料", 
            "系统扩展法", 
            1.000, 
            "采用替代方法，将副产品视为替代产品"
        ));
        
        dataList.add(new TableRowData(
            "原料预处理", 
            "粉尘排放", 
            "物理分配法", 
            0.085, 
            "基于污染物排放量进行环境影响分配"
        ));
        
        return dataList;
    }
    
    /**
     * 表格行数据类
     */
    public static class TableRowData {
        private String processName;
        private String byProductName;
        private String allocationMethod;
        private double allocationFactor;
        private String description;
        
        public TableRowData(String processName, String byProductName, 
                           String allocationMethod, double allocationFactor, String description) {
            this.processName = processName;
            this.byProductName = byProductName;
            this.allocationMethod = allocationMethod;
            this.allocationFactor = allocationFactor;
            this.description = description;
        }
        
        public String getProcessName() { return processName; }
        public String getByProductName() { return byProductName; }
        public String getAllocationMethod() { return allocationMethod; }
        public double getAllocationFactor() { return allocationFactor; }
        public String getDescription() { return description; }
    }
}